package middleware

import (
	"myapp/config"
	"myapp/pkg"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	jwtUtil := pkg.NewJWT(config.Conf.JwtSecret)

	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "请求头缺少 Authorization"})
			c.Abort()
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization 格式必须为 Bearer {token}"})
			c.Abort()
			return
		}

		claims, err := jwtUtil.ParseToken(parts[1])
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"code": 100, "error": "无效的Token: " + err.Error()})
			c.Abort()
			return
		}

		// 将用户信息写入上下文
		c.Set("userID", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("roleID", claims.RoleID)

		c.Next()
	}
}

func JWTAuthMiddlewarePublic() gin.HandlerFunc {
	jwtUtil := pkg.NewJWT(config.Conf.JwtSecret)

	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")

		parts := strings.SplitN(authHeader, " ", 2)
		/*if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization 格式必须为 Bearer {token}"})
			c.Abort()
			return
		}*/

		if len(parts) == 2 && parts[0] == "Bearer" {
			claims, err := jwtUtil.ParseToken(parts[1])
			if err != nil {
				//详情可登录可不登录，所以不能全部返回401
				c.JSON(http.StatusOK, gin.H{"code": 100, "error": "无效的Token: " + err.Error()})
				c.Abort()
				return
			}

			// 将用户信息写入上下文
			c.Set("userID", claims.UserID)
			c.Set("username", claims.Username)
			c.Set("roleID", claims.RoleID)
		}

		c.Next()
	}
}
